<?php

/**
 * Util.php
 *
 * Holds class Util
 *
 * @package Library
 */

/**
 * Util
 *
 * Holds common functions
 *
 * @package Library
 */
class Util {

	public static $microtime = null;
	
	/**
	 * Constructor, doesn't allow access
	 *
	 * @return void
	 */
	private function __construct() {
		//
	}

	/**
	 * Doesn't do anything. Here to load the file.
	 * @return void
	 */
	public static function dummy(){
		Util::$microtime = new Microtime();
	}

	/**
	 * Base 64 decode for URLs (RFC4648)
	 *
	 * @param string $string
	 * @return string
	 */
	public static function base64UrlDecode($string) {
		$string = strtr($string, '-_', '+/');
		return base64_decode($string, true);
	}

	/**
	 * Base 64 encode for URLs (RFC4648)
	 *
	 * @param string $string
	 * @return string
	 */
	public static function base64UrlEncode($string) {
		$string = base64_encode($string);
		return trim(strtr($string, '+/', '-_'), '=');
	}

	/**
	 * Ternany operator
	 *
	 * @param &$x (by reference)
	 * @param $y (optional)
	 * @return mixed
	 */
	public static function ifSet(&$x, $y = null) {
		return isset($x) ? $x : $y;
	}

	/**
	 * Converts variable to boolean representation
	 *
	 * @param mixed $b
	 * @return boolean
	 */
	public static function toBoolean($b) {
		return ('off' == strtolower($b) || "false" == strtolower($b)) ? false : (true == $b);
	}

	/**
	 * Converts all applicable characters to HTML entities
	 *
	 * @param array|string $output
	 * @return array|string
	 */
	public static function quote($output) {
		if(is_array($output)) {
			return array_map(array(__CLASS__, __FUNCTION__), $output);
		}
		return is_string($output) ? htmlentities($output, ENT_QUOTES, 'UTF-8', false) : $output;
	}

	/**
	 * Combines the best of substr() and wordwrap()
	 *
	 * @param string $string
	 * @param integer $length
	 * @param string $suffix (optional)
	 * @return string
	 */
	public static function substrWords($string, $length, $suffix = '...') {
		if(strlen($string) <= $length) {
			return $string;
		}

		$piece = explode(' ', $string);
		$old = $new = '';
		$i = 0;
		while(strlen($old) < $length) {//keep adding words until maximum length is reached
			$new = $old;

			if(0 != $i) {//re-add spaces between words
				$old .= ' ';
			}
			$old .= $piece[$i];//glue together

			$i++;
		}

		if(isset($suffix)) {//add suffix
			$new .= ' ' . $suffix;
		}
		return $new;
	}

	/**
	 * URL-encodes string
	 *
	 * @param string $url
	 * @return string
	 */
	public static function urlEncode($string) {
		// Set to UTF8
		$string = utf8_decode(html_entity_decode($string, ENT_QUOTES, 'UTF-8'));

		// Replace special chars (1-1)
		$string = strtr($string, utf8_decode('ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞàáâãäåçèéêëìíîïðñòóôõöøùúûüýÿþŔŕ'),
		                                     'aaaaaaceeeeiiiidnoooooouuuuybaaaaaaceeeeiiiidnoooooouuuuyybrr');

		// Replace special chars (1-n)
		$string = strtr($string, array(
		utf8_decode('Æ') => 'ae',
		utf8_decode('æ') => 'ae',
		utf8_decode('ß') => 'ss')
		);

		// Normalize
		$string = strtolower($string);
		//$string = str_replace(' ', '-', $string);
		$string = preg_replace('#[^a-z0-9_-]#', '-', $string);
		$string = trim($string, '-');

		// Remove duplicated underscores
		do {
			$old    = $string;
			$string = str_replace('--', '-', $string);
		}
		while($old != $string);

		return $string;
	}

	public static function getMicrotime($microtime = null){
		if(null !== $microtime){
			Util::$microtime = $microtime;
		}
		
		list ( $usec, $sec ) = explode ( " ", Util::$microtime->get());
		return (( float ) $usec + ( float ) $sec);
	}

	public static function ksorti(array &$array){
		return uksort($array,"strcasecmp");
	}

	public static function baseEncode($val, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'){
		$base = strlen($chars);
		$str = "";
		do{
			$i = $val % $base;
			$str = "{$chars[$i]}{$str}";
			$val = ($val - $i) / $base;
		}while($val > 0);
		return $str;
	}

	public static function baseDecode($str, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'){
		$base = strlen($chars);
		$len = strlen($str);
		$val = 0;
		$arr = array_flip(str_split($chars));
		for($i = 0; $i < $len; ++$i) {
//			var_dump($val);
			$val += $arr[$str[$i]] * pow($base, $len-$i-1);
		}
//		var_dump($val);
		return $val;
	}
}
